﻿using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Request.Consume;
using CarEdge.Infrastructure.Dto.Request.Customer;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.Dto.Response.Customer;
using CarEdge.Infrastructure.Dto.Response.Rights;
using CarEdge.Infrastructure.EFCore.MySql;
using CarEdge.Infrastructure.IOC;
using CarEdge.Infrastructure.IOC.Customer;
using CarEdge.Infrastructure.IOC.Dic;
using CarEdge.Infrastructure.IOC.VIP;
using CarEdge.Service.Interface;
using CarEdge.Service.Interface.Customer;
using Crm.Infrastructure.Tools;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CarEdge.Service.Instance.Customer_Service
{
    [Inject_]
    public class Customer_Service : Base_Service,I_Customer_Service
    {
        private readonly Customer_IOC _customer_IOC;
        private readonly Dic_IOC _dic_IOC;
        private readonly VIP_IOC _vIP_IOC;

        public Customer_Service(Customer_IOC customer_IOC, Dic_IOC dic_IOC,VIP_IOC  vIP_IOC)
        {
            _customer_IOC = customer_IOC;
            _dic_IOC = dic_IOC;
            _vIP_IOC = vIP_IOC;
        }
        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> AddCustomer(Customer_Request_Dto dto)
        {
            if(dto.type!= "04021b0100d10030c63c01207ae71b47")
            {
                return Result(0, "会员类型有误！");
            }

            var iq =await  _dic_IOC._dictionary_EFCore.QueryAll(d => d.DId == dto.level).Select(d => d.DName).SingleAsync();

            var source=await _dic_IOC._dictionary_EFCore.QueryAll(d=>d.DId==dto.source).Select(d=>d.DName).SingleAsync();

            Customer customer = new Customer()
            {
                CId = Config.GUID(),
                CAddress = dto.address,
                CAuthor = dto.author,
                CCreateTime = DateTime.Now,
                CDesc = null,
                CFollowTime = DateTime.Parse(dto.followtime!),
                CLevel = iq=="待定"?0:1,
                CName = dto.name,
                CNextTime = DateTime.Parse(dto.nexttime!),
                CPhone = dto.phone,
                CRecord = dto.record,
                CDid = dto.type,
                CRemark = dto.remark,
                CResponsibility = dto.responsibility,
                CStatus = iq == "待定" ? 1 : 2 ,
                CSchool = dto.school,
                CSeasTime = DateTime.Parse( dto.sears!),
                CSource = source,
                CUpdateTime = null,
                CWechat = dto.wechat,
                CRecordCount=0,
                CSuccessPercent= iq == "待定"?0:100,
                CType = dto.type,
            };

            //字典
            var sou=_dic_IOC._dictionary_EFCore.QueryAll(d=>d.DId== dto.source).Single();

            sou.DUserCount=sou.DUserCount+1;

            _dic_IOC._dictionary_EFCore.Update(sou);

            await  _dic_IOC._dictionary_EFCore.SaveChangesAsync();


            //添加会员
            var vipcount =await _dic_IOC._dictionary_EFCore.QueryAll(d => d.DId == dto.type).SingleAsync();

            vipcount.DUserCount = vipcount.DUserCount + 1;

            _customer_IOC._customer_EFCore.Add(customer);

            _dic_IOC._dictionary_EFCore.Update(vipcount);


            var result =await  _dic_IOC._dictionary_EFCore.SaveChangesAsync();
            
            await _customer_IOC._customer_EFCore.SaveChangesAsync();

            return Result(1, "操作成功");

        }
        /// <summary>
        /// 添加跟进记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> AddCustomerRecord(Customer_Record_Request_Dto dto)
        {

            
            var count = await _customer_IOC._customer_Record_EFCore.QueryAll(d => d.CrCId == dto.cid).CountAsync();

            var res=await _dic_IOC._dictionary_EFCore.QueryAll(d=>d.DId==dto.result).Select(d=>d.DName).SingleAsync();

            int getresult = res =="待定" ? 0 : 1;

            CustomerRecord customerRecord = new CustomerRecord()
            {
                CrId = Config.GUID(),
                CrContent = dto.content,
                CrLocation = dto.location,
                CrCId = dto.cid,
                CrCreateTime = DateTime.Now,
                CrDate = DateTime.Parse(dto.date!),
                CrDesc = null,
                CrIsConvert = dto.isconvert,
                CrNextTime = string.IsNullOrEmpty(dto.nexttime) ? null : DateTime.Parse(dto.nexttime),
                CrNo = count + 1,
                CrResult =getresult,
                CrSuccess = dto.success,
                CrAuthor = dto.author,
            };

            var cus=await _customer_IOC._customer_EFCore.QueryAll(d=>d.CId==dto.cid).SingleAsync();

            cus.CSuccessPercent=dto.success;
            cus.CNextTime=Convert.ToDateTime(dto.nexttime);
            if (getresult == 1)
            {
                cus.CStatus = 2;
                cus.CLevel = 1;
                cus.CDid = "8f2eabd9ecf811ef9301902e1656e0d2";

                var iq = await _dic_IOC._dictionary_EFCore.QueryAll(d => d.DId == "8f2eabd9ecf811ef9301902e1656e0d2").SingleAsync();
                iq.DUserCount = iq.DUserCount + 1;
                _dic_IOC._dictionary_EFCore.Update(iq);
                await _dic_IOC._dictionary_EFCore.SaveChangesAsync();

                //新增会员
                Vip vip = new Vip();
                vip.VId = Config.GUID();
                vip.VCid=dto.cid;
                vip.VDid=cus.CDid;
                vip.VCreateTime = DateTime.Now;
                vip.VRecharge = 0;
                vip.VConsumption = 0;

                _vIP_IOC._vIP_EFCore.Add(vip);
                await _vIP_IOC._vIP_EFCore.SaveChangesAsync();


            }
            _customer_IOC._customer_EFCore.Update(cus);
            await  _customer_IOC._customer_EFCore.SaveChangesAsync();

            _customer_IOC._customer_Record_EFCore.Add(customerRecord);
            var result = await _customer_IOC._customer_Record_EFCore.SaveChangesAsync();

            return Result(result);
        }
        /// <summary>
        /// 新增转换客户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Addvip(Customer_Request_Dto dto)
        {
            var cus = await _customer_IOC._customer_EFCore.QueryAll(d => d.CId == dto.id).SingleAsync();
            cus.CLevel = 1;
            cus.CDid = "8f2eabd9ecf811ef9301902e1656e0d2";
            cus.CSuccessPercent = 100;
            cus.CStatus = 2;
            var dic = await _dic_IOC._dictionary_EFCore.QueryAll(d => d.DId == "8f2eabd9ecf811ef9301902e1656e0d2").SingleAsync();
            dic.DUserCount = dic.DUserCount + 1;
            _dic_IOC._dictionary_EFCore.Update(dic);

            CustomerRecord customerRecord = new CustomerRecord()
            {
                CrId = Config.GUID(),
                CrContent = "直接转换",
                CrLocation = "",
                CrCId = dto.id,
                CrCreateTime = DateTime.Now,
                CrDate = DateTime.Now,
                CrDesc = null,
                CrIsConvert = 1,
                CrNextTime = string.IsNullOrEmpty(dto.nexttime) ? null : DateTime.Parse(dto.nexttime),
                CrResult = 1,
                CrSuccess = 100,
                CrAuthor = dto.author,
            };

            var iq=await _customer_IOC._customer_Record_EFCore.QueryAll(d=>d.CrCId == dto.id).ToListAsync();

            if (!iq.Any())
            {
                customerRecord.CrNo = 1;
               
            }
            else
            {
                customerRecord.CrNo = iq.Count() + 1;
            }

            Vip vip = new Vip();
            vip.VId = Config.GUID();
            vip.VCid = dto.id;
            vip.VDid = cus.CDid;
            vip.VCreateTime = DateTime.Now;
            vip.VRecharge = 0;
            vip.VConsumption = 0;

            _vIP_IOC._vIP_EFCore.Add(vip);

            await  _vIP_IOC._vIP_EFCore.SaveChangesAsync();

            _customer_IOC._customer_Record_EFCore.Add(customerRecord);

            await _customer_IOC._customer_Record_EFCore.SaveChangesAsync();

            await _dic_IOC._dictionary_EFCore.SaveChangesAsync();
            _customer_IOC._customer_EFCore.Update(cus);
            var result = await _customer_IOC._customer_EFCore.SaveChangesAsync();
            return Result(1, "转换成功");
        }

        public async Task<Api_Response_Dto> Consumption(Consume_Request_Dto dto)
        {
            var last = _customer_IOC._consume_EFCore.QueryAll(d => d.CId == dto.cid).OrderByDescending(d => d.CCreateTime).Select(d => d.CBalance).FirstOrDefault();
            var c_did = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == dto.cid).SingleOrDefault()!.CDid;
            var key = Convert.ToDouble(_customer_IOC._dictionary_EFCore.QueryAll(d => d.DId == c_did).SingleOrDefault()!.DValue);
            var vipmoney = dto.money * key;
            if (last - vipmoney < 0)
            {
                return Result(0, "没米了,请充值");
            }
            Consume consume = new Consume()
            {
                CVid = dto.cid,
                CCreateTime = DateTime.Now,
                CPid = dto.pid,
                CId = Config.GUID2(),
                CMoney = dto.money,
                CType = 1,
            };
            consume.CBalance = last - vipmoney;
            _customer_IOC._consume_EFCore.Add(consume);
            await _customer_IOC._consume_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }
        /// <summary>
        /// 获取所有的客户
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetAllCustomers(int page = 1, int limit = 10, string key = "")
        {

            var iq = _customer_IOC._customer_EFCore.QueryAll(out int total, page, limit, false, o => o.CCreateTime, d => d.CStatus == 1 && (d.CName!.Contains(key) || d.CDesc!.Contains(key) || d.CAddress!.Contains(key) || d.CPhone!.Contains(key) || d.CQq!.Contains(key) || d.CWechat!.Contains(key) || d.CSchool!.Contains(key) || d.CRemark!.Contains(key)) );

            var data = await iq.Select(d => new Customer_Response_Dto
            {
                id = d.CId,
                name = d.CName,
                address = d.CAddress,
                author = d.CAuthor,
                createtime = d.CCreateTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                followtime = d.CFollowTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                nexttime = d.CNextTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                phone = d.CPhone,
                qq = d.CQq,
                level = d.CLevel,
                mileage = d.CMileage,
                vehiclemodel = d.CVehicleModel,
                record = d.CRecord,
                responsibility = d.CResponsibility,
                school = d.CSchool,
                sears = d.CSeasTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                source = d.CSource,
                status = d.CStatus,
                updatetime = d.CUpdateTime!.Value.ToString("yyyy-MM-dd HH:mm"),
                wechat = d.CWechat,
                type = d.CType,
                success_percent = d.CSuccessPercent ?? 0,


            }).ToListAsync();

            List<string> dList = new List<string>();
            dList.AddRange(data.Select(d => d.type!).ToList());
            dList.AddRange(data.Select(d => d.source!).ToList());
         

            var dics = await _dic_IOC._dictionary_EFCore.QueryAll(d => dList.Contains(d.DId)).ToListAsync();

            var cids = data.Select(d => d.id).ToList();

            var records = await _customer_IOC._customer_Record_EFCore.QueryAll(d => cids.Contains(d.CrCId)).ToListAsync();
            data.ForEach(d =>
            {
                d.record = _customer_IOC._sys_User_EFCore.QueryAll(e => e.Uid == d.record).FirstOrDefault()?.Uname;
                d.responsibility = _customer_IOC._sys_User_EFCore.QueryAll(e => e.Uid == d.responsibility).FirstOrDefault()?.Uname;
                d.author = _customer_IOC._sys_User_EFCore.QueryAll(e => e.Uid == d.author).FirstOrDefault()?.Uname;         
                d.type = dics.Where(e => e.DId == d.type).SingleOrDefault()?.DName;
                d.source = dics.Where(e => e.DId == d.source).SingleOrDefault()?.DName;
                d.record_count = records.Where(e => e.CrCId == d.id).Count();
            });
            //查询出来的数据在内存中 占用空间一般来说非常小

            return Result(1, "ok", new
            {
                total,
                data
            });
        }

        /// <summary>
        /// 获取所有的员工
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> GetAllusers(string key)
        {
            var user =await _customer_IOC._sys_User_EFCore.QueryAll(d=>d.UisBan==0 && d.UisActive==1 && (d.Uaccount!.ToLower().Contains(key.ToLower())|| d.Uname!.ToLower().Contains(key.ToLower()))).ToListAsync();

            List<sys_User_Request_Dto> data = new List<sys_User_Request_Dto>();

            user.ForEach(e =>
            {
                data.Add(new sys_User_Request_Dto
                {
                    id=e.Uid,
                    name=e.Uname,
                });
            });
            return Result(1, data: data);

            
        }
        /// <summary>
        /// 获取单个用户的详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetCustomerById(string id)
        {
            var iq =  _customer_IOC._customer_EFCore.QueryAll(d => d.CId == id);
            if (! iq.Any())
            {
                return Result(0, "参数错误");
            }
            var customer = await iq.SingleAsync();

            
            
            Customer_Response_Dto data = new Customer_Response_Dto()
            {
                address = customer.CAddress,
                author = _customer_IOC._sys_User_EFCore.QueryAll(d => d.Uid == customer.CAuthor).SingleOrDefault()!.Uname,
                createtime = customer.CCreateTime?.ToString("yyyy-MM-dd:HH-mm"),
                followtime = customer.CFollowTime?.ToString("yyyy-MM-dd:HH-mm"),
                level = customer.CLevel,
                name = customer.CName,
                nexttime = customer.CFollowTime?.ToString("yyyy-MM-dd:HH-mm"),
                phone = customer.CPhone,          
                record = _customer_IOC._sys_User_EFCore.QueryAll(d => d.Uid == customer.CRecord).SingleOrDefault()!.Uname,
                responsibility = _customer_IOC._sys_User_EFCore.QueryAll(d => d.Uid == customer.CResponsibility).SingleOrDefault()!.Uname,
                school = customer.CSchool,
                sears = customer.CSeasTime?.ToString("yyyy-MM-dd:HH-mm"),
                source = customer.CSource,
                status = customer.CStatus,
                updatetime = customer.CUpdateTime?.ToString("yyyy-MM-dd:HH-mm"),
                wechat = customer.CWechat,
                remark=customer.CRemark==""?"无":customer.CRemark!,
                type = _dic_IOC._dictionary_EFCore.QueryAll(d=>d.DId==customer.CType).SingleOrDefault()!.DName,

            };
         

            return Result(1, "操作成功", data:data);
        }
        /// <summary>
        /// 获取跟进记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> GetCustomerRecordsById(string id)
        {
            var iq = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == id);

            var iqq = _customer_IOC._customer_Record_EFCore.QueryAll(d => d.CrCId == id);
            if (!await iq.AnyAsync() || !await iq.AnyAsync())
            {
                return Result(0, "参数错误");
            }
            var data =await _customer_IOC._customer_Record_EFCore.QueryAll(d => d.CrCId == id).OrderBy(d=>d.CrCreateTime).Select(d => new Customer_Record_Response_Dto()
            {
                id = d.CrId,
                cid = d.CrCId,
                name = $"第 {d.CrNo} 次跟进",
                content = d.CrContent,
                createtime = d.CrCreateTime!.Value.ToString("yyyy-MM-dd:HH-mm"),
                date = d.CrDate!.Value.ToString("yyyy-MM-dd:HH-mm"),
                desc = d.CrDesc,
                location = d.CrLocation,
                isconvert = d.CrIsConvert,
                nexttime = d.CrNextTime!.Value.ToString("yyyy-MM-dd:HH-mm"),
                no = d.CrNo,
                result = d.CrResult,
                success = d.CrSuccess
            }).ToListAsync();        
            var customer = await iq.SingleAsync();

            data.Insert(0, new Customer_Record_Response_Dto
            {
                id = Config.GUID(),
                no = 0,
                content = "首次添加客户",
                name = "添加客户",
                success = 0,
                location= "-",
                date = customer.CCreateTime!.Value.ToString("yyyy-MM-dd"),
                isconvert = 0,
                result = 0,
                nexttime = customer.CNextTime!.Value.ToString("yyyy-MM-dd"),
                createtime = customer.CCreateTime!.Value.ToString("yyyy-MM-dd")
            });


            return Result(1, "操作成功", data);
        }

        public async Task<Api_Response_Dto> Recharge(Consume_Request_Dto dto)
        {
            var last = _customer_IOC._consume_EFCore.QueryAll(d => d.CId == dto.cid).OrderByDescending(d => d.CCreateTime).Select(d => d.CBalance).FirstOrDefault();
            var customer = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == dto.cid).Single();
            if (last == null || last == 0)
            {
                Consume consume = new Consume()
                {
                    CId = Config.GUID2(),
                    CVid = dto.cid,
                    CCreateTime = DateTime.Now,
                    CBalance = dto.money,
                    CPid = null,
                    CMoney = dto.money,
                    CType = 0,
                };
                _customer_IOC._consume_EFCore.Add(consume);
            }
            else
            {
                Consume consume = new Consume()
                {
                    CId = Config.GUID2(),
                    CVid = dto.cid,
                    CCreateTime = DateTime.Now,
                    CBalance = dto.money,
                    CPid = null,
                    CMoney = last + dto.money,
                    CType = 0,
                };
                _customer_IOC._consume_EFCore.Add(consume);

            }
            customer.CRechargeAmount = customer.CRechargeAmount + dto.money;
            _customer_IOC._customer_EFCore.Update(customer);
            await _customer_IOC._consume_EFCore.SaveChangesAsync();
            await _customer_IOC._customer_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> UpdateCustomer(Customer_Request_Dto dto)
        {
            var iq = _customer_IOC._customer_EFCore.QueryAll(d => d.CId == dto.id);
            if (!iq.Any())
            {
                return Result(0, "参数错误");
            }
            var customer = iq.Single();
            customer.CRemark = dto.remark;
            customer.CAddress = dto.address;
            customer.CName = dto.name;        
            customer.CResponsibility = dto.responsibility;         
            customer.CPhone = dto.phone;                     
            customer.CWechat = dto.wechat;
            customer.CRecord = dto.record;
            customer.CUpdateTime = DateTime.Now;
            _customer_IOC._customer_EFCore.Update(customer);
            await _customer_IOC._customer_EFCore.SaveChangesAsync();
            return Result(1, "操作成功");
        }
    }
}
